
import { useCallback, useEffect, useState } from 'react';
import { Notification } from '@arco-design/web-react';
import { getAllUsers } from '../../../../api/personal';
import { setPermission } from '../../../../api/utils';

import { UserList } from '../../../../common/components/UserList';
import { UserInfo } from '../../../../common/types/conversation';
import { UserConfigForm, UserInfoForm } from './components/UserInfoForm';
import './index.css';
import { useRecoilValue } from 'recoil';
import { userInfoState } from '../../../../store/userInfo';

export const PermissionConfig = () => {

  const [userInfos, setUserInfos] = useState<Array<UserInfo>>([]);
  const [currentUser, setCurrentUser] = useState<UserInfo>();

  const userInfo = useRecoilValue(userInfoState);

  const initData = useCallback(async (user?: UserInfo) => {
    const result = await getAllUsers();
    const { data } = result;
    const { users } = data;
    setUserInfos(users);
    users.length && setCurrentUser(user || users[0]);
  }, []);

  const handleChangeUser = useCallback((user: UserInfo) => {
    setCurrentUser(user);
  }, []);

  const handleSubmit = useCallback(async (values: UserConfigForm) => {
    if (userInfo.id === currentUser?.id) {
      Notification.warning({ content: '不能更改自己的职务' });
      return;
    }

    if (currentUser && currentUser.permission !== values.permission_type) {
      const result = await setPermission(currentUser.id, values.permission_type);
      const { code, msg } = result.data;
      if (code === 200) {
        Notification.info({ content: msg })
        await initData(currentUser);

      } else {
        Notification.warning({ content: '服务器错误' })
      }
      return;
    }

    Notification.warning({ content: '权限设置与原本的一致' });
  }, [userInfo, currentUser]);

  useEffect(() => {
    initData();
  }, []);

  return (
    <div className='all-conversation-wrapper'>
      <div className='all-conversation-sider'>
        {currentUser ? <UserList handleChangeUser={handleChangeUser} data={userInfos} currentUser={currentUser} /> : <></>}
      </div>
      <div className='all-conversation-content'>
        {currentUser ? <UserInfoForm currentUser={currentUser} handleSubmit={handleSubmit} /> : null}
      </div>
    </div>
  )
}